// Objective function
private double Banana(
TVec x,
TVec c,
params object[] o)
{
return 100*Math387.IntPower(x[1] - Math387.IntPower(x[0],2),2) + Math387.IntPower(1-x[0],2);
}
// Analytical gradient and Hessian matrix of the objective function
private void BananaGradHess(
TRealFunction Fun,
TVec Pars,
TVec Consts,
object[] obj,
TVec Grad,
TMtx Hess)
{
double[] Pars = Parameters.PValues1D(0);
Grad[0] = -400.0*(Pars[1]-Math387.IntPower(Pars[0],2))*Pars[0] - 2*(1-Pars[0]);
Grad[1] = 200.0*(Pars[1]-Math387.IntPower(Pars[0],2));
Hess.Values1D[0] = -400.0*Pars[1]+1200*Math387.IntPower(Pars[0],2)+2;
Hess.Values1D[1] = -400.0*Pars[0];
Hess.Values1D[2] = -400.0*Pars[0];
Hess.Values1D[3] = 200.0;
}
private void Example()
{
double[2] Pars;
double fmin;
Matrix iHess =
new Matrix(0,0);
TOptStopReason StopReason;
// initial estimates for x1 and x2
Pars[0] = 0;
Pars[1] = 0;
int iters = Optimization.Marquardt(Banana,BananaGradHess,Pars,
null,
null,
out fmin, iHess,
out StopReason,
TMtxFloatPrecision.mvDouble, 1000, 1.0e-8, 1.0e-8,
null);
// stop if Iters >1000 or Tolerance < 1e-8
}